﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text.Json;
using TALib;
using WeskyQuantDemo.Models;
using WeskyQuantDemo.Services;
using WeskyQuantDemo.Services.BasicServices;

namespace WeskyQuantDemo.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MyQuantController : ControllerBase
    {
        private readonly IQuantDataService _quantDataService;
        public MyQuantController(IQuantDataService quantDataService)
        {
            _quantDataService = quantDataService;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<StockBaseInfo>>> GetStockBaseInfos()
        {
            var apiUrl = "http://127.0.0.1:8080/api/public/stock_info_a_code_name";
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var stockBaseInfos = await _quantDataService.GetStockInfosAsync<IEnumerable<StockBaseInfo>>(apiUrl);
            stopwatch.Stop();
            var elapsed = stopwatch.ElapsedMilliseconds;
            return Ok(stockBaseInfos);
        }

        [HttpPost]
        public async Task<ActionResult<string>> GetHistory()
        {
            var apiUrl = "http://127.0.0.1:8080/api/public/stock_zh_a_hist";
            string today = DateTime.Now.ToString("yyyyMMdd");
            var formData = new Dictionary<string, string>
            {
                 { "symbol", "300532" },
                { "period", "daily" },
                { "start_date", "19900101" },
                { "end_date", today },
                { "adjust", "qfq" }
            };
            var result = await _quantDataService.GetWithQueryParamsAsync(apiUrl, formData);
            IEnumerable<StockHistoryInfo> stockHistoryInfos = JsonSerializer.Deserialize<IEnumerable<StockHistoryInfo>>(result);

            return Ok(stockHistoryInfos);
        }

        [HttpPost]
        public async Task<ActionResult<string>> TestEma()
        {
            var apiUrl = "http://127.0.0.1:8080/api/public/stock_zh_a_hist";
            string today = DateTime.Now.ToString("yyyyMMdd");
            var formData = new Dictionary<string, string>
            {
                 { "symbol", "600519" },
                { "period", "daily" },
                { "start_date", "19900101" },
                { "end_date", today },
                { "adjust", "qfq" }
            };
            var result = await _quantDataService.GetWithQueryParamsAsync(apiUrl, formData);
            IEnumerable<StockHistoryInfo> stockHistoryInfos = JsonSerializer.Deserialize<IEnumerable<StockHistoryInfo>>(result);

            double[] total = stockHistoryInfos.OrderBy(x=>x.日期).Select(x => x.收盘).ToArray();

            List<double> ema12List = BasicIndicators.CalculateEMA(total, 12).Values;
            List<double> ema26List = BasicIndicators.CalculateEMA(total, 26).Values;

            int startIdx = 0;
            int endIdx = total.Length - 1;
            double[] outMacd = new double[total.Length];
            double[] outMacdSignal = new double[total.Length];
            double[] outMacdHist = new double[total.Length];
            int outBegIdx;
            int outNbElement;
            int fastPeriod = 12;    // 快速周期，默认12
            int slowPeriod = 26;    // 慢速周期，默认26
            int signalPeriod = 9;   // 信号线周期，默认9

            // 调用TA-Lib的Macd函数
         //   Core.RetCode retCode = Core.Macd(total, startIdx, endIdx, outMacd, outMacdSignal, outMacdHist, out outBegIdx, out outNbElement, fastPeriod, slowPeriod, signalPeriod);


            ema12List.Reverse();
            ema26List.Reverse();
            // 计算DIF
            var dif = ema12List.Zip(ema26List, (x, y) => x - y).ToList();

            // 计算DEA
            dif.Reverse();
            var dea = BasicIndicators.CalculateEMA(dif, 9).Values.ToList();

            dif.Reverse();
            dea.Reverse();

            // 计算MACD
            var macd = dif.Zip(dea, (difValue, deaValue) => (difValue - deaValue) * 2).ToList();

            // 获取最新（今天）的DIF, DEA, 和 MACD
            var todayDif = dif[0];
            var todayDea = dea[0];
            var todayMacd = macd[0];


            // 获取前一天的DIF, DEA, 和 MACD
            var lastDif = dif[1];
            var lastDea = dea[1];
            var lastMacd = macd[1];
    //        var talibMacd = outMacd.Last();
            return Ok(new
            {
                todayMacd,
                todayDea,
                todayDif,
                lastMacd,
                lastDea,
                lastDif,
 //               talibMacd
            });

        }
    }
}
